"""
Case Type   : gs_checkse工具功能
Case Name   : 验证gs_checkse的A1项确保没有host条目的源地址指定为0.0.0.0/0检测
Create At   : 2024/10/24
Owner       : lihongji
Description :
    1.设置host条目的源地址指定为0.0.0.0/0后检测A1项
Expect      :
    1.设置0.0.0.0/0成功并打印告警信息
History     :
"""
import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from yat.test import Node
from yat.test import macro


class GS_CHECKSE(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.primaryNode = Node('PrimaryDbUser')
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.env_path = macro.DB_ENV_PATH
        self.pg_hba_path = os.path.join(macro.DB_INSTANCE_PATH,
                                        macro.PG_HBA_FILE_NAME)

    def test_gscheckse(self):
        step = ('----step1:设置host条目的源地址指定为0.0.0.0/0后检测A1项'
                'expect:设置0.0.0.0/0成功并打印告警信息----')
        self.log.info(step)
        excute_msg = self.sh_primary.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, param='',
            pghba_param=f'hostnossl all flag 0.0.0.0/0 sha256')
        self.assertTrue(excute_msg)
        gs_checkse_cmd = (f'source {self.env_path};'
                          f'gs_checkse -i A1 --detail;')
        self.log.info(gs_checkse_cmd)
        check_res = self.common.get_sh_result(self.primaryNode, gs_checkse_cmd)
        self.assertIn("Ensure there are no 'host' entries specifying "
                      "the source address as 0.0.0.0/0",
                      check_res, '执行失败' + step)

    def tearDown(self):
        step = '----step2:清理环境  expect:成功----'
        self.log.info(step)
        del_flag = (f"sed -i '/flag/d' {self.pg_hba_path};"
                    f"cat {self.pg_hba_path} | grep flag")
        self.log.info(del_flag)
        del_res = self.common.get_sh_result(self.primaryNode, del_flag)
        self.assertNotIn("flag", del_res, '执行失败' + step)
        self.log.info(f'----{os.path.basename(__file__)} end----')